<template>
  <div class="list-container">
    <el-card class="list-card">
      <div class="search-area">
        <el-form :model="searchForm" :class="{ 'form-mobile': isMobileView }">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="6" class="form-item-wrapper">
              <el-form-item label="车场">
                <el-select 
                  v-model="searchForm.zybLaneDto.depId" 
                  placeholder="请选择车场" 
                  class="full-width-select"
                  filterable
                  clearable
                >
                  <el-option 
                    v-for="item in departmentList" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :xs="24" :sm="12" :md="6" class="form-item-wrapper">
              <el-form-item label="车场">
                <el-select 
                  v-model="searchForm.zybLaneDto.parkId" 
                  placeholder="请选择车场" 
                  class="full-width-select"
                  filterable
                  clearable
                >
                  <el-option 
                    v-for="item in parkList" 
                    :key="item.id" 
                    :label="item.name" 
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :xs="24" :sm="12" :md="6" class="form-item-wrapper">
              <el-form-item label="相机序列号">
                <el-input v-model="searchForm.zybLaneDto.serialNumber" placeholder="请输入相机序列号"></el-input>
              </el-form-item>
            </el-col>
            <!-- <el-col :xs="24" :sm="12" :md="6" class="form-item-wrapper">
              <el-form-item label="车道名称">
                <el-input v-model="searchForm.zybLaneDto.name" placeholder="请输入车道名称"></el-input>
              </el-form-item>
            </el-col> -->
          </el-row>
          <el-row>
            <el-col :span="24" class="button-group">
              <el-button type="primary" @click="handleOpenAll" v-if="!!searchForm.zybLaneDto.depId">一键全开</el-button>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
              <el-button type="danger" @click="handleLogout">退出</el-button>
            </el-col>
          </el-row>
          
        </el-form>
      </div>
      
      <div class="table-area">
        <el-table 
          :data="tableData" 
          v-loading="loading"
          :class="{ 'mobile-table': isMobileView }"
          :header-cell-style="{ background: '#f5f7fa' }"
        >
          <el-table-column 
            prop="parkName" 
            label="车场名称"
            min-width="120"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column 
            prop="name" 
            label="通道名称"
            min-width="120"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column 
            label="操作" 
            :width="isMobileView ? 'auto' : '300'"
            :fixed="isMobileView ? false : 'right'"
          >
            <template #default="{ row }">
              <div class="action-buttons">
                <el-switch
                  v-model="row.isActive"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleAlwaysOpenChange(row)"
                  class="action-switch"
                  :inactive-text="row.isActive === 1 ? '常开' : '常关'"
                />
                <el-button 
                  type="primary" 
                  @click="handleOpenGate(row)"
                  :size="isMobileView ? 'small' : 'default'"
                >开闸</el-button>
                <el-button 
                  type="danger" 
                  @click="handleCloseGate(row)"
                  :size="isMobileView ? 'small' : 'default'"
                >关闸</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-area">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :small="isMobileView"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :popper-class="'custom-pagination'"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getList, getParkInfoList, getDepartList, operateKeepAlive, operateOpen, openAll } from '../api/list'
import type { ListQuery } from '../api/list'
import { useRouter } from 'vue-router'

// 响应式布局相关
const isMobileView = ref(window.innerWidth <= 768)
const handleResize = () => {
  isMobileView.value = window.innerWidth <= 768
}


const router = useRouter()
const handleLogout = () => {
  // 清除用户信息和token
  localStorage.removeItem('userInfo');
  localStorage.removeItem('token');
  
  // 导航到登录页面
  router.push('/login');
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 添加样式
const styles = document.createElement('style')
styles.textContent = `
.list-container {
  padding: 1rem var(--padding-x);
  width: 100%;
  box-sizing: border-box;
  min-height: 100%;
  overflow-y: auto;
  height: 100vh;
}

.list-card {
  margin-bottom: 1rem;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-area {
  margin-bottom: 1.5rem;
}

.form-item-wrapper {
  margin-bottom: 1rem;
}

.full-width-select {
  width: 100%;
}

.button-group {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1rem;
}

.table-area {
  overflow-x: auto;
}

.pagination-area {
  margin-top: 1rem;
  display: flex;
  justify-content: flex-end;
}

@media screen and (max-width: 768px) {
  .list-container {
    padding: 4px var(--padding-x);
    height: calc(100vh - 60px); /* 考虑到可能的顶部导航栏高度 */
    overflow-y: auto;
    -webkit-overflow-scrolling: touch; /* 为 iOS 设备提供平滑滚动 */
  }

  .list-card {
    margin: 0;
    box-shadow: none;
    border-radius: 0;
    height: auto;
    min-height: 100%;
  }

  .button-group {
    justify-content: center;
  }

  .el-table {
    font-size: 0.875rem;
  }

  .el-button {
    padding: 8px 15px;
  }

  .el-form-item__label {
    float: none;
    display: block;
    text-align: left;
    margin-bottom: 0.5rem;
  }

  .pagination-area {
    justify-content: center;
  }

  .el-pagination {
    font-size: 0.875rem;
  }

  .mobile-table {
    width: 100%;
  }

  .action-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    justify-content: flex-end;
  }

  .action-switch {
    margin-right: 0.5rem;
  }

  .el-table .el-table__cell {
    padding: 8px;
  }

  .el-form-item {
    margin-bottom: 12px;
  }
}

/* 自定义滚动条样式 */
.table-area::-webkit-scrollbar {
  height: 6px;
  width: 6px;
}

.table-area::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.table-area::-webkit-scrollbar-track {
  background: #f5f7fa;
}
`
document.head.appendChild(styles)

interface DepartmentItem {
  id: string
  name: string
}

interface ParkItem {
  id: string
  name: string
}

interface TableItem {
  id: string
  parkName: string
  name: string
  isActive: number
  sn: string
}

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const departmentList = ref<DepartmentItem[]>([])
const parkList = ref<ParkItem[]>([])

const searchForm = reactive<ListQuery>({
  pageNo: 1,
  pageSize: 10,
  zybLaneDto: {
    id: '',
    departName: '',
    parkName: '',
    parkId: '',
    name: '',
    number: '',
    type: 0,
    serialNumber: '',
    linkserialNumber: '',
    depId: '',
  }
})

const tableData = ref<TableItem[]>([])

// 获取部门列表
const getDepartmentList = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    const response = await getDepartList({
      userId: userInfo["id"] || '',
      parentId: '',
      parentProjId: '',
      departName: '',
      orgCategory: 1
    })
    
    const { result } = response;
    const list = result.map(item => ({
      id: item.id,
      name: item.departName
    }));
    
    departmentList.value = list;
  } catch (error: any) {
    ElMessage.error(error.message || '获取部门列表失败')
  }
}

// 获取车场列表
const getParkList = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    const response = await getParkInfoList({
      userId: userInfo["id"] || '',
      depId: '',
      name: '',
      parentId: ''
    })

    const { result } = response;
    const list = result.map(item => ({
      id: item.id,
      name: item.name
    }));
    parkList.value = list;
  } catch (error: any) {
    ElMessage.error(error.message || '获取车场列表失败')
  }
}

const handleSearch = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    loading.value = true
    searchForm.pageNo = currentPage.value
    searchForm.pageSize = pageSize.value
    searchForm.zybLaneDto.userId = userInfo["id"] || ''

    const { result } = await getList(searchForm)
    
    tableData.value = result.records.map(item => ({
      id: item.id,
      parkName: item.parkName,
      name: item.name,
      isActive: item.isActive,
      sn: item.serialNumber,
    }))
    total.value = result.total
    ElMessage.success('查询成功')
  } catch (error: any) {
    ElMessage.error(error.message || '查询失败')
  } finally {
    loading.value = false
  }
}

const handleOpenAll = async () => {
  openAll(searchForm.zybLaneDto.depId)
}

const resetSearch = () => {
  searchForm.zybLaneDto = {
    "id": "string",
    "departName": "string",
    "parkName": "string",
    "parkId": "string",
    "name": "string",
    "number": "string",
    "type": 0,
    "serialNumber": "string",
    "linkserialNumber": "string",
    "depId": "string"
  }
  handleSearch()
}

// 处理常开状态改变
const handleAlwaysOpenChange = async (row: TableItem) => {
  try {
    const { code, result } = await operateKeepAlive({
      sn: row.sn,
      lanId: row.id,
      state: !!row.isActive ? 0 : 1
    })
    if (code === 200) {
      ElMessage.success('设置成功')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '设置失败')
  }
}

// 处理开闸
const handleOpenGate = async (row: TableItem) => {
  try {
    const { code } = await operateOpen({
      sn: row.sn,
      lanId: row.id,
      state: 0
    })

    if (code === 200) {
      ElMessage.success('开闸成功')
    }
  } catch (error: any) {
    ElMessage.error(error.message || '开闸失败')
  }
}

// 处理关闸
const handleCloseGate = async (row: TableItem) => {
  try {
    const { code } = await operateOpen({
      sn: row.sn,
      lanId: row.id,
      state: 1
    })
    ElMessage.success('关闸成功')
  } catch (error: any) {
    ElMessage.error(error.message || '关闸失败')
  }
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  handleSearch()
}

onMounted(async () => {
  await Promise.all([
    getDepartmentList(),
    getParkList()
  ])
  handleSearch()
})
</script>

<style scoped>
.list-container {
  padding: 4px;
  height: 100vh;
  overflow-y: auto;
}

.search-area {
  margin-bottom: 20px;
}

.table-header {
  margin-bottom: 20px;
}

.pagination-area {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 确保移动端的表格区域可以正常滚动 */
.table-area {
  width: 100%;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

/* 优化移动端的触摸体验 */
@media (hover: none) and (pointer: coarse) {
  .list-container {
    -webkit-overflow-scrolling: touch;
  }
}
</style>
